// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "Components/GameStateComponent.h"

#include "LyraPlayerSpawningManagerComponent.generated.h"

#define UE_API LYRAGAME_API

class AController;
class APlayerController;
class APlayerState;
class APlayerStart;
class ALyraPlayerStart;
class AActor;

/**
 * @class ULyraPlayerSpawningManagerComponent
 */
UCLASS(MinimalAPI)
class ULyraPlayerSpawningManagerComponent : public UGameStateComponent
{
	GENERATED_BODY()

public:
	UE_API ULyraPlayerSpawningManagerComponent(const FObjectInitializer& ObjectInitializer);

	/** UActorComponent */
	UE_API virtual void InitializeComponent() override;
	UE_API virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
	/** ~UActorComponent */

protected:
	// 工具函数
	UE_API APlayerStart* GetFirstRandomUnoccupiedPlayerStart(AController* Controller, const TArray<ALyraPlayerStart*>& FoundStartPoints) const; // 获取第一个随机未占用的玩家出生点
	
	virtual AActor* OnChoosePlayerStart(AController* Player, TArray<ALyraPlayerStart*>& PlayerStarts) { return nullptr; } // 选择玩家出生点回调
	virtual void OnFinishRestartPlayer(AController* Player, const FRotator& StartRotation) { } // 完成重启玩家回调

	UFUNCTION(BlueprintImplementableEvent, meta=(DisplayName=OnFinishRestartPlayer))
	UE_API void K2_OnFinishRestartPlayer(AController* Player, const FRotator& StartRotation); // 蓝图可实现的完成重启玩家事件

private:

	/** 我们从ALyraGameMode代理这些调用到此组件，以便每个体验可以更轻松地自定义他们想要的复活系统。 */
	UE_API AActor* ChoosePlayerStart(AController* Player); // 选择玩家出生点
	UE_API bool ControllerCanRestart(AController* Player); // 控制器是否可以重启
	UE_API void FinishRestartPlayer(AController* NewPlayer, const FRotator& StartRotation); // 完成重启玩家
	friend class ALyraGameMode; // 友元类
	/** ~ALyraGameMode */

	UPROPERTY(Transient) // 临时属性，不保存
	TArray<TWeakObjectPtr<ALyraPlayerStart>> CachedPlayerStarts; // 缓存的玩家出生点

private:
	UE_API void OnLevelAdded(ULevel* InLevel, UWorld* InWorld); // 关卡添加回调
	UE_API void HandleOnActorSpawned(AActor* SpawnedActor); // 角色生成回调

#if WITH_EDITOR
	UE_API APlayerStart* FindPlayFromHereStart(AController* Player); // 查找从此处开始播放的出生点
#endif
};

#undef UE_API